//
//  AIMyLibraryController.m
//  HNBaseProject
//
//  Created by xujie on 2024/9/15.
//

#import "AIMyLibraryController.h"
#import "DCProductionListViewController.h"
#import "AIMyLibraryTopCell.h"
#import "AIMyLibraryCenterCell.h"
#import "AIMyLibraryBottomCell.h"
#import "AIChargeListController.h"
#import "AIKefuView.h"
#import "YNSSetController.h"
#import "YNSPayVC.h"
#import "AIMyHistoryCreateModel.h"
#import "YNSResultVC.h"
#import "YNSApplePayVC.h"
@interface AIMyLibraryController ()<MxNavigationViewDelegate,UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *listTab;
@property (nonatomic, strong) MxPublicNav *nav;
@property (nonatomic, copy) NSString *money;
@property (nonatomic, strong) NSMutableArray *listArray;

@end

@implementation AIMyLibraryController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F5F8FB"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMony) name:@"buysuccess" object:nil];
    self.listArray = [[NSMutableArray alloc] init];
    self.money = @"";
    [self createUI];
    [self getMoney];//获取余额
    [self getHistoryList];
}

- (void)createUI {
    
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.backgroundColor = [UIColor clearColor];
    self.nav.titleLab.text = NSLocalizedString(@"我的制作", nil);
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    [self.view addSubview:self.listTab];
    [self.listTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.offset(kNavBarHeight);
    }];
    
}

//获取历史
- (void)getHistoryList {

    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/video.video/historyVideo" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if ([dict[@"code"] intValue]==1) {
            [weakSelf.listArray removeAllObjects];
            NSArray *dataArray = [NSArray modelArrayWithClass:[AIMyHistoryCreateModel class] json:dict[@"data"][@"lists"]];
            [weakSelf.listArray addObjectsFromArray:dataArray];
            [weakSelf.listTab reloadData];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

//获取余额
- (void)getMoney {
    MJWeakSelf
    [[DCHttpClient shareClient] requestWithPath:@"api/user/center" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){
            NSString *user_money = [NSString stringWithFormat:@"%@",dict[@"data"][@"user_money"]];
            weakSelf.money = user_money;
            [weakSelf.listTab reloadData];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MJWeakSelf
    if (indexPath.section == 0) {
        
        AIMyLibraryTopCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AIMyLibraryTopCell class])];
        cell.moneyLab.text = self.money;
        return cell;
        
    } else if (indexPath.section == 1) {
        
        AIMyLibraryCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AIMyLibraryCenterCell class])];
        [cell reloadCellWithArray:self.listArray];
        cell.cellClick = ^(NSInteger index) {
            [weakSelf clickHistoryWithIndex:index];
        };
        return cell;
    }
    AIMyLibraryBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AIMyLibraryBottomCell class])];
    cell.cellClick = ^(NSInteger index) {
        [weakSelf showMoreWithIndex:index];
    };
    return cell;
}

- (void)clickHistoryWithIndex:(NSInteger)index {
    if (index == 0) {
        if (self.listArray.count > 0) {
            AIMyHistoryCreateModel *model = self.listArray[0];
            if ([model.state isEqualToString:@"SUCCESS"]) {
                [self gotoResultWithModel:model];
            }
        }
    } else if (index == 1) {
        if (self.listArray.count > 1) {
            AIMyHistoryCreateModel *model = self.listArray[1];
            if ([model.state isEqualToString:@"SUCCESS"]) {
                [self gotoResultWithModel:model];
            }
        }
    } else if (index == 2) {
        if (self.listArray.count > 2) {
            AIMyHistoryCreateModel *model = self.listArray[2];
            if ([model.state isEqualToString:@"SUCCESS"]) {
                [self gotoResultWithModel:model];
            }
        }
    } else {
        if (self.listArray.count > 3) {
            AIMyHistoryCreateModel *model = self.listArray[3];
            if ([model.state isEqualToString:@"SUCCESS"]) {
                [self gotoResultWithModel:model];
            }
        }
    }
}

- (void)gotoResultWithModel:(AIMyHistoryCreateModel *)model {
    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:@"api/video.video/detail" params:@{@"id":model.ID} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if([dict[@"code"] intValue]==1){

            YNSResultVC *resultVc = [[YNSResultVC alloc] init];
            resultVc.fromList = YES;
            resultVc.video_url = dict[@"data"][@"video_url"];
            resultVc.cover_image_url = dict[@"data"][@"image_url"];
            [weakSelf.navigationController pushViewController:resultVc animated:YES];
        } else {

        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        YNSApplePayVC*vc= [[YNSApplePayVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)showMoreWithIndex:(NSInteger)index {
    if (index == 0) {
        AIChargeListController *listVc = [[AIChargeListController alloc] init];
        listVc.type = @"1";
        listVc.pay_status = @"2";
        [self.navigationController pushViewController:listVc animated:YES];
    } else if (index == 1) {
        AIChargeListController *listVc = [[AIChargeListController alloc] init];
        listVc.fromCost = YES;
        listVc.type = @"2";
        listVc.pay_status = @"0";
        [self.navigationController pushViewController:listVc animated:YES];
    } else if (index == 2) {
        AIKefuView *view = [[AIKefuView alloc] init];
        zhPopupController *_zh_popupController = [[zhPopupController alloc] initWithView:view size:view.bounds.size];
        _zh_popupController.presentationStyle = zhPopupSlideStyleTransform;
        _zh_popupController.layoutType = zhPopupLayoutTypeCenter;
        _zh_popupController.dismissOnMaskTouched = YES;
        [_zh_popupController showInView:self.view.window duration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut bounced:NO completion:nil];
        view.cancleClick = ^{
            [_zh_popupController dismiss];
        };
        view.sureClick = ^(NSString * _Nonnull phone) {
            [_zh_popupController dismiss];
            if (phone.length>0) {
                [[DCHelpTool shareClient] dc_callMobile:phone];
            }
        };
    } else {
        YNSSetController *setVc = [[YNSSetController alloc] init];
        [self.navigationController pushViewController:setVc animated:YES];
    }
}

- (UITableView *)listTab {
    
    if (nil == _listTab) {
        _listTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _listTab.backgroundColor = [UIColor clearColor];
        _listTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTab.delegate = self;
        _listTab.dataSource = self;
        _listTab.showsVerticalScrollIndicator = NO;
        _listTab.showsHorizontalScrollIndicator= NO;
        [_listTab registerClass:[AIMyLibraryTopCell class] forCellReuseIdentifier:NSStringFromClass([AIMyLibraryTopCell class])];
        [_listTab registerClass:[AIMyLibraryCenterCell class] forCellReuseIdentifier:NSStringFromClass([AIMyLibraryCenterCell class])];
        [_listTab registerClass:[AIMyLibraryBottomCell class] forCellReuseIdentifier:NSStringFromClass([AIMyLibraryBottomCell class])];
        if (@available(iOS 11.0, *)) {
            _listTab.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _listTab.sectionHeaderTopPadding = 0;
        }
    }
    return _listTab;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 68)];
    headerV.userInteractionEnabled = YES;
    UIImageView *bgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"联合 12"]];
    [headerV addSubview:bgV];
    [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.top.offset(38);
    }];
    
    UILabel *titLab = [[UILabel alloc] init];
    [headerV addSubview:titLab];
    titLab.textColor = [UIColor colorWithHexString:@"#000000"];
    titLab.font = PFRFontSemibold(15);
    [titLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(23);
        make.top.offset(32);
    }];
    
    if (section == 0) {
        titLab.text = NSLocalizedString(@"钻石", nil);
    } else if (section == 1) {
        titLab.text = NSLocalizedString(@"我的制作", nil);
        UIImageView *moreV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"组 255"]];
        moreV.userInteractionEnabled = YES;
        [headerV addSubview:moreV];
        MJWeakSelf
        [moreV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf moreClick];
        }]];
        [moreV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-15);
            make.centerY.mas_equalTo(titLab);
        }];
    } else {
        titLab.text = NSLocalizedString(@"我的工具", nil);
    }
    return headerV;
}

- (void)moreClick {
    DCProductionListViewController *listVc = [[DCProductionListViewController alloc] init];
    [self.navigationController pushViewController:listVc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 68;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if(scrollView == self.listTab) {
    CGFloat sectionHeaderHeight = 68;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
     }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 110;
    } else if (indexPath.section == 1) {
        return 345;
    }
    return 115;
}

- (void)reloadMony {
    [self getMoney];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}


@end
